﻿namespace Klear.Library.Services;
using System.Collections.ObjectModel;
using Klear.Library.Models;
using SQLite;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

public class VisualizationService : IVisualizationService
{
    private readonly IDatabaseService _databaseService;

    public VisualizationService(IDatabaseService databaseService)
    {
        _databaseService = databaseService;
    }

    public async Task<VisualizationModel> GetVisualizationDataAsync()
    {
        var model = new VisualizationModel();

        // 获取当前年份
        var currentYear = DateTime.Now.Year;
        
        // 获取预算数据，添加预算数据到模型中
        model.budget = await _databaseService.GetVisualizationBudgetSettingsAsync();
        
        // 获取收入和支出数据
        for (int i = 1; i <= 12; i++)
        {
            var monthStart = new DateTime(currentYear, i, 1);
            var monthEnd = new DateTime(currentYear, i, DateTime.DaysInMonth(currentYear, i));
            var incomeModels = await _databaseService.GetIncomeAndExpensesAsync(monthStart, monthEnd, "收入");
            var expenseModels = await _databaseService.GetIncomeAndExpensesAsync(monthStart, monthEnd, "支出");

            // 计算总收入和总支出
            var totalIncomeForMonth = incomeModels.Sum(e => e.Amount);
            var totalExpenseForMonth = expenseModels.Sum(e => e.Amount);

            model.totalIncome.Add((float)totalIncomeForMonth);
            model.totalExpense.Add((float)totalExpenseForMonth);
        }

        return model;
    }
}
